// https://www.lintcode.com/problem/validate-binary-search-tree/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: True if the binary tree is BST, or false
     */
    public boolean isValidBST(TreeNode root) {
        // write your code here
        if (root != null) {
            return _isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }
        return true;
    }
    
    private boolean _isValidBST(TreeNode root, int min, int max) {
        if (root != null) {
            if ((max != Integer.MAX_VALUE) && (root.val >= max)) {
                return false;
            }
            if ((min != Integer.MIN_VALUE) && (root.val <= min)) {
                return false;
            }
            boolean isLeft = _isValidBST(root.left, min, root.val);
            boolean isRight = _isValidBST(root.right, root.val, max);
            return isLeft && isRight;
        }
        return true;
    }
}